package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.dao.CameraDataDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.CameraData;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CameraDataService {

    @Autowired
    private Ys7Service ys7Service;

    @Autowired
    private CameraDataDao cameraDataDao;

    @Autowired
    private DeviceDao deviceDao;

    public void captureAndSavePhoto(String deviceSerial) {
        Device device = deviceDao.findBySensorId(deviceSerial);
        if (device == null) {
            throw new RuntimeException("Device not found for sensor ID: " + deviceSerial);
        }

        String picUrl = ys7Service.capturePhoto(deviceSerial);
        CameraData cameraData = new CameraData();
        cameraData.setDevice(device);
        cameraData.setPhotoUrl(picUrl);
        cameraData.setCreateTime(new Date());
        cameraDataDao.save(cameraData);
    }
    public String getLatestPhotoUrl() {
        CameraData latestCameraData = cameraDataDao.findTopByOrderByCreateTimeDesc();
        if (latestCameraData != null) {
            return latestCameraData.getPhotoUrl();
        } else {
            throw new RuntimeException("No camera data found.");
        }
    }
    public CameraData getLatestCameraData() {
        CameraData latestCameraData = cameraDataDao.findTopByOrderByCreateTimeDesc();
        if (latestCameraData == null) {
            throw new RuntimeException("No camera data found.");
        }
        return latestCameraData;
    }

    // 获取摄像头的历史数据
    public List<CameraData> getHistoricalCameraData() {
        List<CameraData> historicalData = cameraDataDao.findAllByOrderByCreateTimeDesc();
        if (historicalData.isEmpty()) {
            throw new RuntimeException("No historical camera data found.");
        }
        return historicalData;
    }
}